#ifndef _BYU_GL_4_H_
#define _BYU_GL_4_H_

#include <stdio.h>

// try to figure out if we are running on a Windows system:
#if defined(_Windows)  || defined(__WINDOWS__) || \
    defined(__WIN32__) || defined(WIN32)       || \
    defined(__WINNT__) || defined(__NT__)      || \
	defined(WINNT)     || defined(_MSC_VER)
# ifndef WINDOWS
#  define WINDOWS
# endif
#endif

// include different files depending on the platform
#if defined(WINDOWS) // Windows needs most work, since VC is not ANSI-compliant
#	include <windows.h>
#	define snprintf _snprintf
#	include <GL/gl.h>
#	include <GL/glu.h>
//#	include <GL/glut.h>
#   include "glut.h"
#	pragma comment(lib,"opengl32.lib")
#	pragma comment(lib,"glu32.lib")
#	pragma comment(lib,"glut32.lib")
#	pragma comment(lib,"glut32.dll")
#elif defined(__APPLE__) // Apple Frameworks need different include paths
#	include <OpenGL/gl.h>
#	include <OpenGL/glu.h>
#	include <GLUT/glut.h>
#else // Pretty much any non-Apple non-Windows system the same
#	include <GL/gl.h>
#	include <GL/glu.h>
#	include <GL/glut.h>
#endif

#include <assert.h>

void (*udraw)(void);
void (*ureshape)(int,int);

int w,h;
HDC	  hDC=NULL;		// Private GDI Device Context
float *screen = 0;

inline void set(int x, int y, float r, float g, float b, float a=1) {
	if (!screen) return;
	assert(x >= 0 && x < w && y >= 0 && y < h);
	screen[4*(x + w*(y)) + 0] = r;
	screen[4*(x + w*(y)) + 1] = g;
	screen[4*(x + w*(y)) + 2] = b;
	screen[4*(x + w*(y)) + 3] = a;
}
inline float getR(int x, int y) { return screen[4*(x + w*(y)) + 0]; }
inline float getG(int x, int y) { return screen[4*(x + w*(y)) + 1]; }
inline float getB(int x, int y) { return screen[4*(x + w*(y)) + 2]; }
inline float getA(int x, int y) { return screen[4*(x + w*(y)) + 3]; }

static int owin;

int W,H;
int centerX, centerY;
float aspect;

void resize(int wd, int ht) {
	W = wd; H = ht;
    centerX = W/2; centerY = H/2;
	if (screen) delete[] screen;
	screen = new float[w*h*4];
	ureshape(wd,ht);
	glutPostRedisplay();
}

void reshape(int wd, int ht) 
{
	W = wd; H = ht;
	glViewport(0,0,wd,ht);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	aspect = wd/((float)ht);
	float _near = 0.8; // pretty far away, so we see clipping
	float _far = 2000.0;
	gluPerspective(90,aspect,_near,_far);
/*	float tmp[16] = {
		1/aspect,0,0,0,
		0,1,0,0,
		0,0,(_far+_near)/(_near-_far),-1,
		0,0,2*_far*_near/(_near-_far),0
	};
	glMultMatrixf(tmp);
*///	gluLookAt(0,.4,1, 0,0,0, 0,1,0);
}

float *rgbatex2d() {
	static float *ans = 0;
	if (ans) return ans;
	ans = new float[64*64*4];
	for (int x=0; x<64; x++) 
		for (int y=0; y<64; y++) {	
			ans[(x*64+y)*4+0] = ((x&15)<8)^((y&15)<8);
			ans[(x*64+y)*4+1] = ((x&31)<16)^((y&31)<16);
			ans[(x*64+y)*4+2] = (x<32)^(y<32);
			ans[(x*64+y)*4+3] = x/64.0f;
		}
	return ans;
}

#endif
